package com.cy.src.common.activity;

import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import com.cy.src.common.R;


/**
 * @author CY
 * @since 2016/5/12 15:20
 * email tmxdyf@163.com
 */
public abstract class ToolBarActivity extends CommonActivity {

    protected ViewGroup mRootView;
    private boolean isUpEnabled;

    /**
     * {@link #getContentViewId()} And {@link #getContentView 随便重写哪个方法，但一定要重写一个}
     * 优先调用{@link #getContentView()}
     *
     * @return 返回布局Id
     */
    protected int getContentViewId() {
        return 0;
    }

    protected View getContentView() {
        return null;
    }

    /**
     * Toolbar 自定义包含Toolbar视图
     *
     * @return 返回包含Toolbar视图
     */
    protected Toolbar getToolbar() {
        return null;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mRootView = (ViewGroup) getLayoutInflater().inflate(R.layout.layout_commom, null);

        Toolbar toolBar;
        if (getToolbar() == null) {
            toolBar = (Toolbar) getLayoutInflater().inflate(R.layout.layout_toolbar, mRootView, false);
        } else {
            toolBar = getToolbar();
        }

        mRootView.addView(toolBar);

        View contentView;

        if (getContentView() != null) {
            contentView = getContentView();
        } else if (getContentViewId() != 0) {
            contentView = getLayoutInflater().inflate(getContentViewId(), mRootView, false);
        } else {
            throw new IllegalStateException("请重写this#getContentView()或者this#getContentViewId()，优先调用getContentView()");
        }

        mRootView.addView(contentView);
        setContentView(mRootView);
        setSupportActionBar(toolBar);
    }


    /**
     * 返回上一界面
     *
     * @param enabled true 显示返回上一级界面
     */
    protected void setDisplayHomeAsUpEnabled(boolean enabled) {
        isUpEnabled = enabled;
        getSupportActionBar().setDisplayHomeAsUpEnabled(enabled);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home && isUpEnabled) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }
}


